/**
 * Created by sjg on 17/9/25.
 *
 * /routes/v5/wechat.js 的工具方法
 *
 */

var ItbUserModel = require('../../../common/mysql/mapping/ItbUserModel');
var TgSearchTagModel = require('../../../common/mysql/mapping/TgSearchTagModel');
var ItbNotificationModel = require('../../../common/mysql/mapping/ItbNotificationModel');
var TgTypeModel = require('../../../common/mysql/mapping/TgTypeModel');
var TgSpecialTopicModel = require('../../../common/mysql/mapping/TgSpecialTopicModel');
var TgKeywordModel = require('../../../common/mysql/mapping/TgKeywordModel');
var TgOutlineModel = require('../../../common/mysql/mapping/TgOutlineModel');
var TgDesignDocModel = require('../../../common/mysql/mapping/TgDesignDocModel');
var TgUserDocModel = require('../../../common/mysql/mapping/TgUserDocModel');
var TgUserPageModel = require('../../../common/mysql/mapping/TgUserPageModel');
var TgUserPcModel = require('../../../common/mysql/mapping/TgUserPcModel');
var TgDesignPcModel = require('../../../common/mysql/mapping/TgDesignPcModel');
var ItbBuyTmplModel = require('../../../common/mysql/mapping/ItbBuyTmplModel');
var ItbTmplPriceModel = require('../../../common/mysql/mapping/ItbTmplPriceModel');
var ItbTemplateModel = require('../../../common/mysql/mapping/ItbTemplateModel');
var ItbItemsModel = require('../../../common/mysql/mapping/ItbItemsModel');
var ItbDocTypeModel = require('../../../common/mysql/mapping/ItbDocTypeModel');
var ItbSceneModel = require('../../../common/mysql/mapping/ItbSceneModel');
var ItbMemberModel = require('../../../common/mysql/mapping/ItbMemberModel');
var ItbTmplPageModel = require('../../../common/mysql/mapping/ItbTmplPageModel');
var TgDesignPageModel = require('../../../common/mysql/mapping/TgDesignPageModel');
var ItbActivityRModel = require('../../../common/mysql/mapping/ItbActivityRModel');
var ItbActivityModel = require('../../../common/mysql/mapping/ItbActivityModel');
var ItbTmplSetModel = require('../../../common/mysql/mapping/ItbTmplSetModel');

var labUtil = require('./labUtil');
var luaSearchUtil = require('./luaSearchUtil');
var tg3Util = require('./tg3Util');
var ApiComUtil = require('./CommonUtil');
var CommonUtil = require('../../../common/util/CommonUtil');
var SJGNode = require('./../../sjg/common/tg/SJGNode');
var SJGTG = require('./../../sjg/common/tg/SJGTG');
var SJGTGV3 = require('./../../sjg/common/tg3/SJGTGV3');
var SJGNodeV3 = require('./../../sjg/common/tg3/SJGNodeV3');
var GroupObj = require('./../../sjg/kernel/obj/GroupObj');
var FColor = require('./../../sjg/kernel/color/FColor');
var GlobalData = require('./../../sjg/z/GlobalData');
var SJGPage = require('./../../sjg/kernel/cont/SJGPage');
var GCJ_CLASS_TYPE = require('./../../sjg/common/GCJ_CLASS_TYPE');

var CONFIG = require('../../../common/config');
var CODE = require('../../../common/code');
var superagent = require('superagent');
var async = require( 'async'); // 同步控制
var rpcFunc=require('../../routes/rpcSrv/rpcFunc.js');

var moment = require('moment');


var wechatUtil = (function(){

    function wechatUtil(){

    }
    // 统一返回 json
    wechatUtil.ret_func_json = function (success, msg, data, res){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    };

    /**
     * 切换作品到指定模版样式
     * @param userId 用户id
     * @param docId 当前作品id
     * @param designId 指定的模版id
     * @param callback 回调
     *         error: 错误原因
     *         {"productId":123456, "designId":789, "thumbs":[ "http://oss-img.jpg", "http://oss-img.jpg" ]}
     *
     * */
    wechatUtil.changeProductByDesign = function(userId, docId, designId, callback){

        //#####################################################
        // 查找用户文档
        var ent1 = new TgUserDocModel({
            doc_id: docId,
            del_flg: 0
        });
        ent1.findFromDB(function(err1, ret1) {
            if (err1) {
                console.log('wechatUtil.js [changeProductByDesign] Find UserDoc Err: ' + err1);
                return callback(err1, null);
            }

            if (ret1 && ret1.length>0) {
                var userDocInfo = ret1[0];

                if(userDocInfo.design_id == designId || designId<=0) {
                    // 无需切换模版,直接获取
                    //#####################################################
                    // 获取页预览图
                    getDocPgThumbs(docId, function(getErr, thumbs){
                        if(getErr) {
                            console.log('wechatUtil.js [changeProductByDesign] getDocPgThumbs(1) Err: '+getErr);
                            //return callback(getErr, null);
                        }
                        var retData = {
                            productId: docId,
                            designId: userDocInfo.design_id||0,
                            thumbs: []
                        };

                        if(thumbs && thumbs.length>0) {
                            //#####################################################
                            // 取到直接返回
                            retData.thumbs = thumbs;
                            return callback(null, retData);

                        } else {
                            //#####################################################
                            // 未取到,重新排版
                            rpcFunc.typesetTGDoc(docId, function (rpcRet) {
                                // 再次获取页预览图
                                getDocPgThumbs(docId, function(getErr2, thumbs2){
                                    if(getErr2) {
                                        console.log('wechatUtil.js [changeProductByDesign] getDocPgThumbs(2) Err: '+getErr2);
                                        return callback(getErr2, null);
                                    }
                                    retData.thumbs = thumbs2||[];
                                    return callback(null, retData);
                                });
                            });
                        }
                    });

                } else {
                    // 需要切换模版
                    //#####################################################
                    // 获取模版信息
                    var ent2 = new TgDesignDocModel({
                        design_id: designId,
                        del_flg: 0
                    });
                    ent2.findFromDB(function(err2, ret2){
                        if(err2) {
                            console.log('wechatUtil.js [changeProductByDesign] Find DesignDoc Err: ' + err2);
                            return callback(err2, null);
                        }

                        if(ret2 && ret2.length>0) {
                            var designInfo = ret2[0];

                            // 检查提纲是否相同
                            if(userDocInfo.tg_id!=designInfo.tg_id || userDocInfo.map_id!=designInfo.map_id) {
                                return callback('模版不匹配', null);
                            }

                            //#####################################################
                            // 解析[用户文档]提纲树
                            var docData = JSON.parse(userDocInfo.data);
                            var docTgTree = new SJGTGV3();
                            docTgTree.fromJson(docData, docData.version);

                            // 微调对象数据
                            var strDocFtData = (userDocInfo.finetune_data||'[]')
                                .replace(/\n/g,'\\n').replace(/\t/g,'').replace(/\r/g,'')
                                .replace(/[\x00-\x09\x0B-\x1F\x7F-\x9F]/g, "");
                            var arrDocFtData = JSON.parse(strDocFtData);
                            var arrDocSJGPage = [];
                            if(arrDocFtData && arrDocFtData.length>0){
                                for(var i=0; i<arrDocFtData.length; i++) {
                                    var page = new SJGPage(new GlobalData());
                                    page.fromJsonOfFineTune(arrDocFtData[i], docData.version);
                                    arrDocSJGPage.push(page);
                                }
                            } else {
                                return callback('用户文档数据异常', null);
                            }

                            //#####################################################
                            // 解析[模版]提纲树
                            var tmplData = JSON.parse(designInfo.data||'{}');
                            var tmplTgTree = new SJGTGV3();
                            tmplTgTree.fromJson(tmplData, tmplData.version);

                            // 解析微调对象数据
                            var strTmplFtData = (designInfo.finetune_data||'[]')
                                .replace(/\n/g,'\\n').replace(/\t/g,'').replace(/\r/g,'')
                                .replace(/[\x00-\x09\x0B-\x1F\x7F-\x9F]/g, "");
                            var arrTmplFtData = JSON.parse(strTmplFtData);
                            var arrTmplSJGPage = [];
                            if(arrTmplFtData && arrTmplFtData.length>0){
                                for(var i=0; i<arrTmplFtData.length; i++) {
                                    var page = new SJGPage(new GlobalData());
                                    page.fromJsonOfFineTune(arrTmplFtData[i], tmplData.version);
                                    arrTmplSJGPage.push(page);
                                }
                            } else {
                                return callback('模版数据异常', null);
                            }

                            //#####################################################
                            // 更新目标模版提纲数据
                            var relations = [];
                            for(var i=0; i<tmplTgTree.root.children.length; i++){
                                var tmplNode = tmplTgTree.root.children[i];

                                // 循环用户文档找对应节点
                                for(var m=0; m<docTgTree.root.children.length; m++) {
                                    var docNode = docTgTree.root.children[m];

                                    if(tmplNode && docNode
                                        && tmplNode.type==docNode.type// 节点类型相同
                                        && tmplNode.o==docNode.o) {// 0表示普通节点／1表示可选／2表示新增节点

                                        var tNodeNm = (tmplNode.topic||'').toLowerCase();
                                        var dNodeNm = (docNode.topic||'').toLowerCase();
                                        if(tNodeNm && tNodeNm.length>0 && dNodeNm && dNodeNm.length>0
                                            && tNodeNm==dNodeNm) {// 节点名称相同

                                            if(docNode.h==0) {// 未隐藏
                                                // 拷贝内容
                                                tmplNode.value = docNode.value;
                                            }
                                        }
                                    }
                                }
                            }

                            //#####################################################
                            // TODO 暂不处理微调数据

                            //#####################################################
                            // 更新用户文档
                            var updEnt = new TgUserDocModel({
                                doc_id: docId,
                                tg_id: designInfo.tg_id,
                                map_id: designInfo.map_id,
                                design_id: designInfo.design_id,// 更新设计模版
                                data: tmplTgTree.toJson() || '',// 更新提纲树
                                finetune_data: '',// 清除微调
                                finetune_flg: 0
                            });
                            updEnt.updateToDB(function(updErr){
                                if(updErr) {
                                    console.log('wechatUtil.js [changeProductByDesign] Update UserDoc Err: '+updErr);
                                    return callback(updErr, null);
                                }

                                // 清除page／pc
                                //labUtil.delDocPgPc(userDocInfo.user_id, docId, function(delErr){
                                //    if(delErr) {
                                //        console.log('wechatUtil.js [changeProductByDesign] Del UserDocPg Err: '+delErr);
                                //    }

                                    //#####################################################
                                    // 排版
                                    rpcFunc.typesetTGDoc(docId, function (rpcRet) {
                                        // 获取页预览图
                                        getDocPgThumbs(docId, function(getErr, thumbs){
                                            if(getErr) {
                                                console.log('wechatUtil.js [changeProductByDesign] getDocPgThumbs(3) Err: '+getErr);
                                                return callback(getErr, null);
                                            }
                                            var retData = {
                                                productId: docId,
                                                designId: designId,
                                                thumbs: thumbs||[]
                                            };
                                            return callback(null, retData);
                                        });
                                    });
                                //});
                            });

                        } else {
                            return callback('未找到对应模版', null);
                        }
                    });
                }

            } else {
                return callback('未找到用户文档', null);
            }
        });

        //#####################################################
        // 获取文档页预览图
        function getDocPgThumbs(docId, cb) {
            var pgEntity = new TgUserPageModel({
                doc_id: docId,
                del_flg:0
            });
            pgEntity.getPageInfoById(function(err, retPages){
                if(err) {
                    return cb(err, null);
                }

                var thumbs = [];
                if(retPages && retPages.length > 0) {
                    for(var j in retPages){
                        var pg = retPages[j];

                        // TODO 只要有未生成预览图就报错
                        if (pg.thumb == null || pg.thumb.trim().length == 0) {
                            return cb('生成预览图失败', null);
                        }

                        thumbs.push(pg.thumb);
                    }
                }

                return cb(null, thumbs);
            });
        }
    };

    /**
     * 获取当天可用模板列表
     * @param callback 回调
     *         error: 错误原因
     *         list: [{id:989, typeL:1}]
     *
     * */
    wechatUtil.getTodayTmplList = function(callback){
        var timeStr = new moment().format('YYYY-MM-DD HH:mm:ss');
        var pageNum = 0;
        var pageSize = 1;
        var use = 301; // 小程序
        (new ItbTmplSetModel()).getTmplSetListWithTimeAndUse(timeStr, use, pageNum, pageSize, function(getTmplSetsErr, sets){
            if(getTmplSetsErr || !sets || sets.length <=0) {
                getTmplSetsErr = getTmplSetsErr ? getTmplSetsErr : '暂无模板';
                return callback(getTmplSetsErr, null);
            }
            // 获取指定模板集合中的模板列表
            var ts = sets[0];
            var pN = 0;
            var pS = 0; // 不限列表个数
            (new ItbTmplSetModel()).getTmplListByTmplSetId(ts.ts_id,pN,pS,function(getTmplListErr, tmpls){
                if(getTmplListErr || !tmpls || tmpls.length <=0) {
                    getTmplListErr = getTmplListErr ? getTmplListErr : '暂无模板';
                    return callback(getTmplListErr, null);
                }

                var data = {};
                data.list = tmpls;
                data.title = ts.title;
                data.desc = ts.desc;
                return callback(null, data);
            });
        });
    };

    return wechatUtil;

})();

module.exports = wechatUtil;